<script setup lang="ts">
import { ref, onMounted, computed, watch,defineProps, defineEmits } from "vue";
import { Book,try_delete_book,try_borrow_book } from "./book";
import { UseLibraryState } from "../library_state";
import { ElNotification,ElTable } from "element-plus";
import EditBookForm from "./EditBookForm.vue";

const state=UseLibraryState()
const props=defineProps({
  books:Array<Book>,
  page_index:Number,
  page_size:Number,
  max_page_index:Number,
  is_loading:Boolean
})
onMounted(()=>{

})
const emits=defineEmits(['next_page','previous_page','jump_to'])
// const book_index_offset=computed(()=>(props.page_index!-1)*props.page_size!)
const get_index=(index:number)=>{
  return index+1+(props.page_index!-1)*props.page_size!
}

const next_page=()=>{
  if (props.page_index!>=props.max_page_index!) return
  emits('next_page',props.page_index!+1)
}

const previous_page=()=>{
  if (props.page_index!<=1) return
  emits('previous_page',props.page_index!-1)
}

const jump_to_page=(target:number)=>{
  target=Math.min(props.max_page_index!,target)
  target=Math.max(1,target)
  if (target==props.page_index!) {
    return
  }
  emits('jump_to',target)
}

const delete_row=async (rid:number)=>{
  can_delete.value=false
  const book = props.books![rid];
  if (!book) {
    return
  }
  try {
    const deleted=await try_delete_book(book.id)
    ElNotification.success({
      message:`删除书籍[${deleted.bookName}]成功!`,
      title:'Success',
      duration:5000,
    })
    // emits('refresh')
    props.books?.splice(rid,1)
  } catch (error) {
      ElNotification.error({
      message:`删除书籍失败!`+error,
      title:'Error',
      duration:10000,
    })
  }
  can_delete.value=true
}

const can_delete=ref(true)

const table_ref=ref<any>()
const expanded_rows=ref<number[]>([])
const expand_row=(row:any,col:any,event:any)=>{

  const idx=expanded_rows.value!.indexOf(row.id)
  if(idx>=0){
    expanded_rows.value!.splice(idx,1)
  }else{
    expanded_rows.value=[row.id]
  }
  // console.dir(expanded_rows.value)
}
const row_key=(row:any)=>row.id

const show_edit_dialog=(row:Book)=>{
  editing_book.value=row
  dialogVisible.value=true
}

const dialogVisible=ref(false)
const editing_book=ref<Book>()
const book_updated=(book:Book)=>{
  dialogVisible.value=false
  const idx=props.books!.findIndex(b=>b.id==book.id)
  if (idx>=0) {
    props.books!.splice(idx,1,book)
  }
}

const borrow_book=async (rid:number)=>{
  const bid=props.books![rid].id
  try {
    const record=await  try_borrow_book(bid)
    ElNotification.success({
      message:'登记借书成功!',
      title:'Success',
      duration:5000,
    })
  } catch (error) {
        ElNotification.error({
      message:'登记借书失败!\n'+error,
      title:'Error',
      duration:10000,
    })
  }
}
</script>

<template>
  <div class="w-full grid-row-fr-auto">
    <el-table
      ref="table_ref"
      stripe
      border
      v-loading="is_loading"
      :data="books"
      highlight-current-row
      empty-text="没有数据..."
      header-cell-class-name="table-header"
      :row-key="row_key"
      :expand-row-keys="expanded_rows"
      @row-click="expand_row"
    >
      <el-table-column type="expand" label="+">
        <template #default="scope">
          <div class="flex justify-center gap-4">
            <el-button v-if="state.can_manage_book" type="primary" @click="show_edit_dialog(scope.row)">编辑</el-button>
            <el-popconfirm title="确认删除?"
            @confirm="delete_row(scope.$index)">
              <template #reference>
                <el-button
                  v-if="state.can_manage_book"
                  type="danger"

                  :disabled="!can_delete"
                  >删除</el-button
                >
              </template>
            </el-popconfirm>
            <el-button v-if="state.can_borrow" type="primary" @click="borrow_book(scope.$index)">借阅</el-button>
            <el-tag v-if="!state.is_login" type="info">请先登录</el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column type="index" :index="get_index" width="60" label="No" />
      <el-table-column prop="bookName" label="书名"></el-table-column>
      <el-table-column prop="author" label="作者" width="300"></el-table-column>
      <el-table-column prop="publisher" label="出版商" width="300"></el-table-column>
    </el-table>
    <el-pagination
      layout="prev,pager,next"
      :page-count="max_page_index"
      class="justify-self-center mt-4"
      background
      @prev-click="previous_page()"
      @next-click="next_page()"
      @current-change="jump_to_page"
    >
    </el-pagination>
  </div>
    <el-dialog
    v-model="dialogVisible"
    title="书籍编辑"
    width="400px"
  >
  <EditBookForm
  :book="editing_book!"
  @updated="book_updated"></EditBookForm>
  </el-dialog>
</template>

<style scoped>
.grid-row-fr-auto {
  display: grid;
  grid-template-rows: auto 1fr;
  grid-template-columns: 1;
}
</style>
<style>
.table-header {
  @apply text-xl;
}
</style>
